package com.example.myrecyclerview;

import android.util.Log;

import com.example.myrecyclerview.bean.Shop;
import com.example.myrecyclerview.utils.StreamTool;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ShopLoader {

    private static String path = "http://file.nidama.net/class/mobile_develop/data/bookstore.json";

    public List<Shop> download() {
        List<Shop> shops = null;
        InputStream in = null;
        try {
            shops = new ArrayList<>();
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestMethod("GET");
//            Log.d("<TEST>:", "回应代码："+conn.getResponseCode());
            if (conn.getResponseCode() == 200) {
                in = conn.getInputStream();
                shops = parseJSON(in);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            Log.d("<TEST>:", "访问链接失败:" + e.toString());
        } catch (IOException e) {
            e.printStackTrace();
            Log.d("<TEST>:", "访问链接失败:" + e.toString());
        }
        return shops;
    }

    /*
     *解析json字符串并返回一个List
     */
    private static List<Shop> parseJSON(InputStream in){
        List<Shop> list = null;
        try {
            list = new ArrayList<>();
//           String str = StreamTool.streamToString(in);
//            System.out.println(str);
            byte[] bytes = StreamTool.stream2Byte(in);//这里用到了StreamTool工具类这里是把输入流转化为字节数组
            String str = new String (bytes,"UTF-8");//因为服务器设置了返回编码为GBK，这里也设置编码方式为GBK
            Log.d("<TEST>:","解析成功");
            JSONObject jsonObject = new JSONObject(str);//将json字符串转化为JSONArray
            String shops = jsonObject.getString("shops");
            JSONArray jsonArray = new JSONArray(shops);
            for(int i =0;i< jsonArray.length();i++){
                JSONObject shopJsonObject = jsonArray.getJSONObject(i);//循环JSONArray获得每一个JSONObject对象
                String name = shopJsonObject.getString("name");
                double latitude = shopJsonObject.getDouble("latitude");
                double longitude = shopJsonObject.getDouble("longitude");
                String memo = shopJsonObject.getString("memo");
                list.add(new Shop(name,latitude,longitude,memo));
            }
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("<TEST>io","输入流读取错误");
        } catch (JSONException e) {
            e.printStackTrace();
            Log.e("<TEST>json","json数组转换错误");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}
